package io.jft.doll.ui.setting

import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.databinding.Observable
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import com.bumptech.glide.Glide
import com.g.base.appContent
import com.g.base.extend.dp
import com.g.base.extend.observeExOnce
import com.g.base.extend.progressDialog
import com.g.base.extend.toast
import com.g.base.help.glide.GlideChaceHelp
import com.g.base.help.ioResultToMainThread
import com.g.base.room.entity.UserEntity
import com.g.base.room.repository.Status
import com.g.base.token.TokenManage
import com.g.base.ui.BaseActivity
import com.g.base.ui.recyclerView.MultiTypeAdapter
import com.g.base.ui.recyclerView.setupRecyclerView
import io.jft.doll.BuildConfig
import io.jft.doll.R
import io.jft.doll.databinding.ViewRecycleBinding
import io.jft.doll.model.bindModel.ButtonBind
import io.jft.doll.model.bindModel.TextTipSwitchBind
import io.jft.doll.model.viewModel.OauthViewModel
import io.jft.doll.router.RouterPage

/**
 * Created by G on 2017/11/25 0025.
 */

@Route(path = RouterPage.SettingActivity)
class SettingActivity : BaseActivity<ViewRecycleBinding>() {
    override var hasToolbar: Boolean = true
    private lateinit var adapter: MultiTypeAdapter
    private val oauthViewModel by lazy { ViewModelProviders.of(this).get(OauthViewModel::class.java) }

    private val soundBind by lazy {
        val soundPlay = getSharedPreferences("setting", Context.MODE_PRIVATE).getBoolean("roomSound", true)
        TextTipSwitchBind("游戏声音", "是否播放背景音乐", true, soundPlay).apply {
            isChecked.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
                override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                    getSharedPreferences("setting", Context.MODE_PRIVATE).edit()
                            .putBoolean("roomSound", isChecked.get() == true)
                            .apply()
                }
            })
        }
    }

    private val cleanCacheBind by lazy {
        var isCleanIng = false
        TextTipSwitchBind("清理缓存", "清除图片缓存 ${GlideChaceHelp.getCacheSize()}")
                .apply {
                    setOnClickListener {
                        if (isCleanIng) {
                            toast("正在清理图片缓存,请勿重复操作")
                            return@setOnClickListener
                        }
                        isCleanIng = true
                        ioResultToMainThread(
                                {
                                    Glide.get(appContent).clearDiskCache()
                                },
                                {
                                    toast("清理图片缓存成功...")
                                    isCleanIng = false
                                    tip.set("清除图片缓存 ${GlideChaceHelp.getCacheSize()}")
                                }
                        )
                    }
                }
    }
    private val versionInfoBind by lazy {
        TextTipSwitchBind("版本信息", "当前版本号:${BuildConfig.VERSION_NAME}", hasMore = true)
                .apply {
                    setOnClickListener {
                        ARouter.getInstance().build(RouterPage.AboutActivity).navigation(this@SettingActivity)
                    }
                }
    }
    private val feedBackBind by lazy {
        TextTipSwitchBind("意见反馈", "提出您意见 帮助我们完善", hasMore = true)
                .apply {
                    setOnClickListener {
                        ARouter.getInstance().build(RouterPage.FeedBackActivity).navigation(this@SettingActivity)
                    }
                }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.view_recycle)
        setupView()
        showContentView()
    }

    override fun onTokenChange(data: UserEntity?) {
        signOutBind.visible.set(data != null)
    }

    private val signOutBind by lazy {
        val token = TokenManage.getToken()
        ButtonBind("退出登录", true, token != null).apply {
            setOnClickListener {
                oauthViewModel.signOut().progressDialog().observeExOnce(this@SettingActivity) {
                    if (it.status != Status.Loading) {
                        TokenManage.cleanToken()
                    }
                }
            }
        }
    }

    private fun setupView() {
        toolbar.title = "设置"
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_toolbar_24dp)
        toolbar.setNavigationOnClickListener { finish() }

        adapter = setupRecyclerView(contentView.recyclerView)
        adapter.layoutHelpers = listOf(
                LinearLayoutHelper(1, 2).also { it.setMargin(0, 8.dp(), 0, 8.dp()) },
                LinearLayoutHelper(1, 2).also { it.setMargin(0, 8.dp(), 0, 8.dp()) },
                LinearLayoutHelper(0, 1).also { it.setMargin(0, 8.dp(), 0, 8.dp()) }
        )

        adapter.renderItems.add(soundBind)
        adapter.renderItems.add(cleanCacheBind)
        adapter.renderItems.add(versionInfoBind)
        adapter.renderItems.add(feedBackBind)
        adapter.renderItems.add(signOutBind)
        adapter.notifyDataSetChanged()
    }
}